package com.sdx.console.promote.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.BaseEntity;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.sdx.common.entity.DictBusiness;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.common.utils.Utils;
import com.sdx.console.order.service.FinOrderService;
import com.sdx.console.promote.entity.PromoteCommission;
import com.sdx.console.promote.service.PromoteCommissionService;
import com.sdx.console.system.service.DictBusinessService;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


/**
 * 佣金定义 接口
 */
@RequestMapping("/promote/promoteCommission")
@Controller
public class PromoteCommissionController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(PromoteCommissionController.class);
    private static final String MODEL = "/promote/promoteCommission";


    @Resource
	private PromoteCommissionService promoteCommissionService;

    @Autowired
    private DictBusinessService dictBusinessService;

    @Resource
    private FinOrderService finOrderService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
        List<DictBusiness> moduleList = dictBusinessService.getModule();
        view.addObject("moduleList",moduleList);
        view.addObject("orderTypes",finOrderService.selectOrderType(null));
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("promote.promoteCommission.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("promote.promoteCommission.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer tenantId,Integer orderType) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        PromoteCommission promoteCommission = promoteCommissionService.queryPromoteCommission(orderType,tenantId);
        view.addObject("promoteCommission", promoteCommission);
		setPageParam(view,request);
		try {
			view.addObject("promoteCommissionJson", JacksonUtils.toJsonString(promoteCommission,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("promote.promoteCommission.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);


        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("promote.promoteCommission.query")
    @ResponseBody
    public JsonResult<PageQuery> list(PromoteCommission condtion,HttpServletRequest request)
    {
        CoreUser user = getLoginUser(request);
        condtion.setTenantId(user.getTenantId());
        PageQuery page = condtion.getPageQuery();
        promoteCommissionService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,PromoteCommission promoteCommission,HttpServletRequest request
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/cover/"+dir+"/";
		String bucketName = "sdxcomm";
		CoreUser user = getLoginUser(request);

    	if (isNew) {
            PromoteCommission commission = promoteCommissionService.queryPromoteCommission(promoteCommission.getOrderType(), user.getTenantId());
            if(commission==null){
                BaseEntity baseEntity = promoteCommissionService.selectOrderType(promoteCommission.getOrderType());
                promoteCommission.setModuleId(Integer.parseInt(baseEntity.get("moduleId").toString()));
                promoteCommission.setTenantId(user.getTenantId());
                promoteCommission.setUpdatedBy(user.getId().intValue());
                promoteCommission.setUpdatedName(user.getName());
                promoteCommission.setUpdatedTime(new Date());
                promoteCommissionService.save(promoteCommission);
            }else{
                result = JsonResult.failMessage("产品类型重复");
            }
		} else {
			promoteCommission.setUpdatedBy(user.getId().intValue());
			promoteCommission.setUpdatedName(user.getName());
			promoteCommission.setUpdatedTime(new Date());
			promoteCommissionService.updateTemplate(promoteCommission);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("promote.promoteCommission.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)PromoteCommission promoteCommission,HttpServletRequest request
		)
    {

        return save(true,promoteCommission,request
		);
    }

    @PostMapping("/update.json")
    @Function("promote.promoteCommission.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  PromoteCommission promoteCommission,HttpServletRequest request
		) {
		return save(false,promoteCommission,request
		);
    }


   
    @GetMapping("/view.json")
    @Function("promote.promoteCommission.query")
    @ResponseBody
    public JsonResult<PromoteCommission>queryInfo(Integer tenantId) {
        PromoteCommission promoteCommission = promoteCommissionService.queryById( tenantId);
        return  JsonResult.success(promoteCommission);
    }

    @PostMapping("/delete.json")
    @Function("promote.promoteCommission.del")
    @ResponseBody
    public JsonResult delete(String ids,HttpServletRequest request) {
        CoreUser user = getLoginUser(request);
        List<String> idList = Utils.strToList(ids,",");
        promoteCommissionService.batchDelPromoteCommission(idList,user.getTenantId());
        return JsonResult.success();
    }

    @PostMapping("/check.json")
    @ResponseBody
    public JsonResult check(Integer orderType,HttpServletRequest request) {
        JsonResult result = JsonResult.success();
        CoreUser coreUser = getLoginUser(request);
        PromoteCommission commission = promoteCommissionService.queryPromoteCommission(orderType, coreUser.getTenantId());

        if(commission!=null){
            result = JsonResult.failMessage("产品类型重复");
        }
        return result;
    }
    

}
